package com.fingard.dsp.bank.dbobj.seq;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

import com.fingard.FGBiz;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.helpers.dbhelpers.InsertHelper;

/**！！注意：需在finally里显示调用close()方法*/
public class SeqDataHelper {
	private static final int maxTabCount = 10;
	
	public static int getMaxTabCount(){
		return maxTabCount;
	}
	
	private Connection partDbconn = null;
	private String tenant = "";
	
	/**！！注意：需在finally里显示调用close()方法
	 * @param 租户
	 * @param 日期*/
	public SeqDataHelper(String pTenant, Date pPartDate) throws Exception{
		tenant = pTenant;
		partDbconn = FGBiz.partTable.getLoaclDbConnByPart(tenant, pPartDate);
	}
	
	/**需在finally里显示调用close()方法*/
	public void close(){
		if(partDbconn != null){
			try{
				partDbconn.close();
			}catch(Exception ex){
				FGBiz.limitMsg.exception("ReceiptDataHelper.closePartDbConn", ex);
			}
		}
	}
	
	private static String getTableName(String pActNum){
		int sum = 0;
		for(int i=0;i<pActNum.length();i++){
			sum += pActNum.charAt(i);
		}
		return "SEQDATA" + (sum%maxTabCount);
	}
	
	public int insertSeqData(SeqData pData) throws Exception{
		String tabName = getTableName(pData.ownAct);
		pData.createdOn = new Date();
		int rowAff = InsertHelper.insertObject(partDbconn, tabName, pData);
		if(rowAff == 1){
			return 1;
		}else{
			throw new Exception("写入"+tabName+"的影响行数："+rowAff);
		}
	}
	
	/**根据本方流水号取对方流水号
	 * @throws SQLException */
	public String getOppSeq(String pOwnSeq, String pOwnAct, String pSrcSys) throws SQLException{
		String tabName = getTableName(pOwnAct);
		String sql = "select OPPSEQ from "+tabName+" where OWNSEQ=? and OWNACT=? and SRCSYS=?";
		Object[] objs = new Object[3];
		objs[0] = pOwnSeq;
		objs[1] = pOwnAct;
		objs[2] = pSrcSys;
		Object retObj = JDBCHelper.execScalar(partDbconn, sql, objs);
		if(retObj != null){
			return retObj.toString();
		}
		return null;
	}
}
